#include "KcpConnect.h"
#include "BaseMsg.h"
#include <string.h>


int udp_output(const char *buf, int len, ikcpcb *kcp, void *user)
{
    auto p = (KcpConnect*)user;
    char buffer[len+8];
    UdpConnect::intToByte((int)BaseMsg::MSG_HEAD_TEPE_CONTENT,buffer);
    UdpConnect::intToByte(p->GetSeeeid(),buffer+4);
    memcpy(buffer+8,buf,len);
    p->SendUdp(buffer,len+8);
    return 0;
}
KcpConnect::KcpConnect(std::shared_ptr<UdpConnect> conn_,uint32_t id):conn(conn_),sessid(id)
{
    kcp =  ikcp_create(id, (void*)this);
    ::ikcp_nodelay(kcp, 0, 10, 0, 0);
    ::ikcp_wndsize(kcp, 128, 128);
    kcp->output = udp_output;
}
KcpConnect::~KcpConnect()
{
    delete kcp;

}
void KcpConnect::Update()
{
    ikcp_update(kcp, iclock());
}
void KcpConnect::SendUdp(const char* buf,int len)
{
    conn->send(buf,len);
}
void KcpConnect::Send(char* buf,int len)
{
    //TODO:这里需要改
    //conn->send(buf,len);
    ::ikcp_send(kcp, buf, len);
}
int KcpConnect::Recv(char* buf,int len)
{ 
    //TODO:
    char data[len];
    int n = conn->recv(data,len);
    ::ikcp_input(kcp, data, n);
    return ::ikcp_recv(kcp, buf, len);
}
void KcpConnect::Close()
{
    SendSessionStatue(BaseMsg::MSG_HEAD_TEPE_CLOSE);
}
void KcpConnect::Connect()
{
    SendSessionStatue(BaseMsg::MSG_HEAD_TEPE_CONNECT);
}
void KcpConnect::ConnectSuccess()
{
    SendSessionStatue(BaseMsg::MSG_HEAD_TEPE_CONNECT_ACK);
}

void KcpConnect::SendSessionStatue(int type)
{
    char buf[8];
    UdpConnect::intToByte(type,buf);
    UdpConnect::intToByte(sessid,buf+4);
    conn->send(buf,8);

}


